'''
Author: cw
Date: 2025-08-15
Description: ...
'''
import time
import aiohttp
from utils import http_util


class WxApiMgr:
    def __init__(self, appid: str, secret: str):
        self.appid = appid
        self.secret = secret
        self.token = None

    async def get_cache_token(self):
        """获取token"""
        if self.token and (time.time() - self.token.get('cache_time') < 7000):
            return self.token.get('access_token')
        self.token = {
            'cache_time': int(time.time()),
            ** await self.get_token(self.appid, self.secret)
        }
        return self.token.get('access_token')

    async def get_token(self, appid: str, secret: str):
        """获取token"""
        url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}'
        res = await http_util.aio_get(url, timeout=3)
        if not (res and res.get('access_token')):
            raise Exception(f'获取token失败,res={res}')
        return res


    async def get_temp_media(self, binary_data: bytes):
        """上传临时素材"""
        token = await self.get_cache_token()
        url = f'https://api.weixin.qq.com/cgi-bin/media/upload?access_token={token}&type=image'
        data = aiohttp.FormData()
        data.add_field(
            "media",
            binary_data,
            filename="%s.jpg" % time.time(),
            content_type="image/jpeg",
        )
        return await http_util.aio_post(url, data=data, timeout=10, fmt='text')


    async def message_custom(self, openid: str, msg_type: str, **kwargs: dict):
        """发送客服消息"""
        token = await self.get_cache_token()
        url = f'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={token}'
        data = {
            "touser": openid,
            "msgtype": msg_type,
            # "image": {
            #     "media_id": "MEDIA_ID"
            # }
            **kwargs
        }
        return await http_util.aio_post(url, json=data, timeout=10)
